package cbs.jdtag;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JOptionPane;

import cbs.jdtag.DataModel2.Alignment;
import cbs.jdtag.DataModel2.Token;

public class UserInputParser {

	private static transient final Logger LOGGER = Logger.getLogger(UserInputParser.class.getName());
	
	public static void parse(String cmd) {
		DataModel2 dm = AppContext.getDM();
		
		LOGGER.log(Level.FINE, "Invoked for \"{0}\"....", cmd);
		
		try {
			if (cmd.matches("(" + dm.getKey(0) + "[0-9]+)"
					+ "\\s(" + dm.getKey(0) + "[0-9]+)")) { // i.e. a0 a0
			
				doWork(cmd, dm.getKey(0), dm.getKey(0));
			}
			else if (cmd.matches("(" + dm.getKey(1) + "[0-9]+)"
					+ "\\s(" + dm.getKey(1) + "[0-9]+)")) { // i.e. b3 b3
			
				doWork(cmd, dm.getKey(1), dm.getKey(1));
			}
			else if (cmd.matches("(" + dm.getKey(0) + "[0-9]+)+"
					+ "\\s(" + dm.getKey(1) + "[0-9]+)+")) { // i.e. a1a3a5 b0b1b2
			
				doWork(cmd, dm.getKey(0), dm.getKey(1));
			}
			else {
				LOGGER.log(Level.FINE, "Illegal input \"{0}\"!", cmd);
				AppContext.mainView.setStatusText("Illegal input!");
			}
		}
		catch (NullPointerException e) {
			LOGGER.log(Level.FINE, "Illegal input \"{0}\"!", cmd);
			AppContext.mainView.setStatusText("Illegal input!");
			return;
		}
	}
	
	private static void doWork(String cmd, String srcKey, String tgtKey) {
		DataModel2 dm = AppContext.getDM();
		
		LOGGER.log(Level.FINE, "Doing work for: cmd=\"{0}\", src key=\"{1}\", tgt key=\"{2}\"....", new Object[]{cmd, srcKey, tgtKey});
		
		String blocks[] = cmd.split(" ");
		Alignment a = dm.new Alignment();
		String nodes[];
		
		nodes = blocks[0].split(srcKey);
		for (int k = 1; k < nodes.length; ++k) {
			
//			Token t = dm.getTokenByPos(srcKey, Integer.valueOf(nodes[k].trim()));
			Token t = dm.getTokenById(srcKey, Integer.valueOf(nodes[k].trim()));
			a.addSrcToken(t);
			t.alignments.add(a);
		}
		
		nodes = blocks[1].split(tgtKey);
		for (int k = 1; k < nodes.length; ++k) {
			
//			Token t = dm.getTokenByPos(tgtKey, Integer.valueOf(nodes[k].trim()));
			Token t = dm.getTokenById(tgtKey, Integer.valueOf(nodes[k].trim()));
			a.addTgtToken(t);
			t.alignments.add(a);
		}
		
		dm.saved = false;
		
		if (dm.alignmentContains(a)) {
			dm.alignmentRemove(a);
			LOGGER.log(Level.FINE, "Alignment removed \"{0}\".", cmd);
			AppContext.mainView.setStatusText("Alignment removed.");
		}
		else {
			dm.alignmentAdd(a);
			LOGGER.log(Level.FINE, "Alignment added \"{0}\".", cmd);
			AppContext.mainView.setStatusText("Alignment added.");
		}
	}
}
